﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace AAA.ResultSet
{
    public class HtmlTableResultSet : AbstractResultSet
    {
        private HtmlElement _htmlTable;
        private bool _hasHeaderRow;

        public HtmlTableResultSet(HtmlElement htmlTable)
            : this(htmlTable, false)
        {
        }

        public HtmlTableResultSet(HtmlElement htmlTable, bool hasHeaderRow)
        {
            _htmlTable = htmlTable;
            _hasHeaderRow = hasHeaderRow;
        }

        public override bool Load()
        {
            bool isSuccess = false;
            HtmlElementCollection rows;
            HtmlElementCollection cols;
            string[] strValues;
            try
            {
                if (_htmlTable == null)
                {
                    ErrorMessage = "Can't load the data source (reason : HtmlTable is null).";
                    return false;
                }

                rows = _htmlTable.GetElementsByTagName("tr");

                if (rows == null)
                {
                    ErrorMessage = "Can't load the data source (reason : table row is null).";
                    return false;
                }

                if (rows.Count == 0)
                {
                    ErrorMessage = "Can't load the data source (reason : table doesn't contain any rows).";
                    return false;
                }
/*
                for (int i = 0; i < rows.Count; i++)
                {
                    string strHTML = rows[i].InnerHtml;
                }
*/
                cols = rows[0].GetElementsByTagName(_hasHeaderRow ? "th" : "td");
                for (int i = 0; i < cols.Count; i++)
                {
                    AddColumn("Column" + i);
                }

                int iStartRow = _hasHeaderRow ? 1 : 0;

                for (int i = iStartRow; i < rows.Count; i++)
                {
                    cols = rows[i].GetElementsByTagName("td");
                    strValues = new string[ColumnCount];

                    for (int j = 0; j < Math.Min(strValues.Length, cols.Count); j++)
                        strValues[j] = cols[j].InnerText;
                    AddRow(strValues);
                }

                isSuccess = true;
            }
            catch (Exception ex)
            {
                ErrorMessage = ex.Message + "," + ex.StackTrace;
                isSuccess = false;
            }

            return isSuccess;
        }
    }
}
